<?php
class Account_model extends CI_Model {
	
	function Account_model() {
		parent::__construct();
		$this->load->database();
	}
	
	function delete($username) {
		$this->db->where('username',$username);
		$this->delPermission($username);
		return $this->db->delete('accounts');
	}
	
	function update($username, $data) {
		$this->db->where('username',$username);
		return $this->db->update('accounts', $data);
	}
	
	function get($username = FALSE) {
		if($username===FALSE) {
			$query = $this->db->get('accounts');
			return $query->result_array();
		}else {
			$this->db->where('username', $username);
			$query = $this->db->get('accounts');
			return $query->first_row();
		}
	}
	
	function is_exist($account){
		$this->db->where('username', $account['username']);
		$this->db->where('password', $account['password']);
		$this->db->where('status', 'Enable');
		$query = $this->db->get ( 'accounts' );
		return ($query->num_rows () > 0);
	}
	
	function add($data) {
		$this->db->where('username', $data['username']);
		$query = $this->db->get('accounts');
		if($query->num_rows() == 1) {
			return FALSE;
		}else {
			$this->inPermission($data['username']);
			return $this->db->insert('accounts',$data);
			
		}
	}
	
	private function inPermission($username) {
		$this->db->insert('accounts_permissions',array('username'=>$username));		
	}
	
	private function delPermission($username) {
		$this->db->where('username', $username);
		$this->db->delete('accounts_permissions');
	}
}